import express from 'express'
import path from 'path'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import compress from 'compression'
import cors from 'cors'
import helmet from 'helmet'
import msgRoutes from './routes/msg.routes'





const CURRENT_WORKING_DIR = process.cwd()
const app = express()



// parse body params and attache them to req.body
// app.use(bodyParser.json({strict: false}))
app.use(bodyParser.json({strict: false}))
app.use(bodyParser.urlencoded({ 
    extended: false,                 
    limit:    2*1024*1024           //限制-2M
 }))
app.use(cookieParser())
app.use(compress())
// secure apps by setting various HTTP headers
app.use(helmet())
// enable CORS - Cross Origin Resource Sharing
app.use(cors())

app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist')))

// app.use((req,res,next)=>{
// 	let chunk = ''
// 	req.on('data',(data)=>{chunk+=data})
// 	req.on('end',()=>{
// 		try{
// 			req.chunk = JSON.parse(chunk)
// 		}catch(err){
// 			req.chunk = chunk
// 			console.log(err)
// 		}
// 		next()
// 	})
// })


// mount routes
app.use('/', msgRoutes)


// // Catch unauthorised errors
// app.use((err, req, res, next) => {
//   if (err.name === 'UnauthorizedError') {
//     res.status(401).json({"error" : err.name + ": " + err.message})
//   }else if (err) {
//     res.status(400).json({"error" : err.name + ": " + err.message})
//     console.log(err)
//   }
// })

export default app
